Popular Searches
Popular Course Categories
Popular Courses

Converting Strings into Primitive Values

Converting Strings into Primitive Values

Wrapper Classes, Autoboxing, and Enumerations

Converting Strings into Primitive Values in Java

Course: Core Java Training

Topic: Converting Strings into Primitive Values

Course Link: Core Java Training Course

Demo Link: Register for a Course Demo

Website: JustAcademy Official Website


1. Introduction to String Conversion

In Java, a String is an object used to represent a sequence of characters. Many applications receive information as text, including user input, configuration settings, form values, API responses, and data read from files.

When a program needs to perform calculations or logical operations on this information, it often needs to convert the text into a primitive data type such as int, double, float, long, or boolean.

This process is called string parsing or converting a string into a primitive value. Java provides static methods in wrapper classes to perform these conversions.

For example, the string "100" is text, not a number. Using Integer.parseInt("100") converts it into the primitive integer value 100, which can then be used in arithmetic operations.

Why Is String Conversion Important?

  • To convert keyboard input into numbers for calculations.
  • To process numeric values received from files or external services.
  • To validate and interpret form data.
  • To perform mathematical operations on values represented as text.
  • To interpret textual flags as Boolean values.
  • To work with command-line arguments, which are supplied as strings.

2. Understanding Primitive Data Types

Java has eight primitive data types. Most can be parsed from strings using methods provided by their corresponding wrapper classes. A char is handled differently because Java does not provide a Character.parseChar() method.

Primitive Type Wrapper Class Parsing Method Example
byte Byte Byte.parseByte() Byte.parseByte("12")
short Short Short.parseShort() Short.parseShort("1200")
int Integer Integer.parseInt() Integer.parseInt("100")
long Long Long.parseLong() Long.parseLong("500000")
float Float Float.parseFloat() Float.parseFloat("12.5")
double Double Double.parseDouble() Double.parseDouble("19.99")
boolean Boolean Boolean.parseBoolean() Boolean.parseBoolean("true")
char Character No direct parse method "A".charAt(0)

3. Converting a String into an int

The Integer.parseInt() method converts a valid string representing an integer into a primitive int.

Syntax

int variableName = Integer.parseInt(stringValue);

Example

public class StringToIntExample {
    public static void main(String[] args) {
        String numberText = "150";
        int number = Integer.parseInt(numberText);

        System.out.println("Number: " + number);
        System.out.println("After adding 50: " + (number + 50));
    }
}

Output:

Number: 150
After adding 50: 200

Explanation: The string "150" is parsed into the integer value 150. The program can then perform arithmetic with the converted value.

Important Rules for Integer Parsing

  • The string must represent a valid integer within the range of int.
  • Positive and negative integer strings are accepted.
  • A decimal point is not valid in an integer string.
  • Invalid text or a value outside the supported range causes a NumberFormatException.
int a = Integer.parseInt("250");   // Valid
int b = Integer.parseInt("-25");   // Valid
// int c = Integer.parseInt("25.5"); // NumberFormatException
// int d = Integer.parseInt("hello"); // NumberFormatException

4. Converting a String into a double

The Double.parseDouble() method converts a valid floating-point string into a primitive double. It is useful for measurements, percentages, averages, and other decimal calculations.

Syntax

double variableName = Double.parseDouble(stringValue);

Example

public class StringToDoubleExample {
    public static void main(String[] args) {
        String priceText = "249.75";
        double price = Double.parseDouble(priceText);

        System.out.println("Price: " + price);
        System.out.println("Price with tax: " + (price * 1.18));
    }
}

Output:

Price: 249.75
Price with tax: 294.705

Explanation: The text "249.75" is converted into a primitive double. The converted value can be multiplied or used in other mathematical operations.

Note: Floating-point arithmetic can produce small precision differences because many decimal fractions cannot be represented exactly in binary. For financial calculations that require exact decimal arithmetic, consider using BigDecimal.

5. Converting a String into a float

The Float.parseFloat() method converts a valid numeric string into a primitive float. A float uses less storage than a double but provides less precision.

Example

public class StringToFloatExample {
    public static void main(String[] args) {
        String temperatureText = "36.5";
        float temperature = Float.parseFloat(temperatureText);

        System.out.println("Temperature: " + temperature);
        System.out.println("After adding 1.5: " + (temperature + 1.5f));
    }
}

Output:

Temperature: 36.5
After adding 1.5: 38.0

The suffix f indicates a float literal in Java. The value returned by Float.parseFloat() is already a primitive float.

6. Converting a String into a long

The Long.parseLong() method converts a valid integer string into a primitive long. It is useful when a number may exceed the range of the int type.

Example

public class StringToLongExample {
    public static void main(String[] args) {
        String populationText = "8500000000";
        long population = Long.parseLong(populationText);

        System.out.println("Population: " + population);
        System.out.println("After adding 1000: " + (population + 1000));
    }
}

Output:

Population: 8500000000
After adding 1000: 8500001000

The value exceeds the maximum positive int value but fits within the range of a signed long.

7. Converting a String into a short

The Short.parseShort() method converts a valid integer string into a primitive short. The value must fit within the range -32,768 to 32,767.

Example

public class StringToShortExample {
    public static void main(String[] args) {
        String numberText = "1200";
        short number = Short.parseShort(numberText);

        System.out.println("Short value: " + number);
        System.out.println("After adding 300: " + (number + 300));
    }
}

Output:

Short value: 1200
After adding 300: 1500

Notice that arithmetic involving a short generally produces an int result because Java promotes smaller integer types during arithmetic.

8. Converting a String into a byte

The Byte.parseByte() method converts a valid integer string into a primitive byte. The value must be between -128 and 127.

Example

public class StringToByteExample {
    public static void main(String[] args) {
        String numberText = "100";
        byte number = Byte.parseByte(numberText);

        System.out.println("Byte value: " + number);
        System.out.println("After adding 10: " + (number + 10));
    }
}

Output:

Byte value: 100
After adding 10: 110

If a string contains a number outside the byte range, parsing fails with a NumberFormatException.

9. Converting a String into a boolean

The Boolean.parseBoolean() method converts a string into a primitive boolean. It returns true only when the string equals "true", ignoring letter case. Other values, including null, produce false.

Example

public class StringToBooleanExample {
    public static void main(String[] args) {
        String firstText = "true";
        String secondText = "FALSE";
        String thirdText = "yes";

        boolean first = Boolean.parseBoolean(firstText);
        boolean second = Boolean.parseBoolean(secondText);
        boolean third = Boolean.parseBoolean(thirdText);

        System.out.println(first);
        System.out.println(second);
        System.out.println(third);
    }
}

Output:

true
false
false

Important: Boolean.parseBoolean("yes") returns false; it does not throw an exception. If an application accepts values such as yes/no, 1/0, or on/off, write explicit validation logic rather than relying on this method alone.

10. Converting a String into a char

Java does not provide a Character.parseChar() method. To obtain a character from a string, use charAt() after checking that the string contains at least one character.

Example

public class StringToCharExample {
    public static void main(String[] args) {
        String letterText = "Java";
        char letter = letterText.charAt(0);

        System.out.println("First character: " + letter);
    }
}

Output:

First character: J

The index begins at zero, so charAt(0) returns the first UTF-16 code unit. Calling charAt(0) on an empty string throws a StringIndexOutOfBoundsException. Also, some Unicode characters require two UTF-16 code units, so a single char does not always represent a complete Unicode character.

11. Difference Between parse Methods and valueOf Methods

Wrapper classes commonly provide both parse... and valueOf methods. Both can convert suitable numeric text, but they return different types.

Method Return Type Example
Integer.parseInt("100") int Primitive integer
Integer.valueOf("100") Integer Integer wrapper object
Double.parseDouble("12.5") double Primitive decimal
Double.valueOf("12.5") Double Double wrapper object
Boolean.parseBoolean("true") boolean Primitive Boolean value
Boolean.valueOf("true") Boolean Boolean wrapper object

Example of parseInt() and valueOf()

public class ParseAndValueOfExample {
    public static void main(String[] args) {
        String text = "500";

        int primitiveValue = Integer.parseInt(text);
        Integer wrapperValue = Integer.valueOf(text);

        System.out.println(primitiveValue + 100);
        System.out.println(wrapperValue + 200);
    }
}

Output:

600
700

Use parsing methods when you need primitive values. Use valueOf() when a wrapper object is required, such as when working with collections that store objects.

12. Converting Strings with Different Number Formats

Integer parsing methods can accept a radix, which specifies the number base used to interpret the string. Common number systems include decimal (base 10), binary (base 2), and hexadecimal (base 16).

Example: Binary and Hexadecimal Parsing

public class RadixParsingExample {
    public static void main(String[] args) {
        int binaryValue = Integer.parseInt("1010", 2);
        int hexadecimalValue = Integer.parseInt("FF", 16);

        System.out.println("Binary value: " + binaryValue);
        System.out.println("Hexadecimal value: " + hexadecimalValue);
    }
}

Output:

Binary value: 10
Hexadecimal value: 255

The second argument tells Java how to interpret the digits. The string "1010" means ten in base 2, while "FF" means 255 in base 16.

13. Handling Invalid String Values

When a numeric string contains invalid characters or represents a value outside the target type's range, Java numeric parsing methods generally throw a NumberFormatException. Programs should handle invalid input so they can report the problem clearly instead of terminating unexpectedly.

Example Using try-catch

public class InvalidNumberExample {
    public static void main(String[] args) {
        String numberText = "12AB";

        try {
            int number = Integer.parseInt(numberText);
            System.out.println("Number: " + number);
        } catch (NumberFormatException e) {
            System.out.println("Invalid integer input.");
        }

        System.out.println("Program continues.");
    }
}

Output:

Invalid integer input.
Program continues.

The try block contains the operation that may fail. If parsing throws NumberFormatException, the matching catch block handles it, and the program continues with the next statement.

Common Reasons for NumberFormatException

  • The string contains alphabetic characters, such as "abc".
  • The string contains a decimal point when parsing an integer, such as "15.5".
  • The value is outside the target type's permitted range.
  • The string is empty or contains only whitespace.
  • The input includes unexpected symbols, such as "$250".

14. Trimming Whitespace Before Parsing

Parsing methods do not automatically remove surrounding whitespace from numeric strings. If text may contain spaces at the beginning or end, call trim() or strip() before parsing, depending on the application's whitespace requirements.

public class TrimBeforeParsingExample {
    public static void main(String[] args) {
        String numberText = "  250  ";

        int number = Integer.parseInt(numberText.trim());

        System.out.println(number + 50);
    }
}

Output:

300

In modern Java, strip() is available for Unicode-aware whitespace stripping. Neither method removes arbitrary symbols from the middle of a string; validate the input format before parsing.

15. Practical Example: Reading Command-Line Arguments

Java command-line arguments are supplied through the String[] args parameter of the main() method. To use an argument as a number, convert it from a string first.

public class CommandLineAddition {
    public static void main(String[] args) {
        if (args.length < 2) {
            System.out.println("Please provide two integers.");
            return;
        }

        try {
            int first = Integer.parseInt(args[0]);
            int second = Integer.parseInt(args[1]);

            System.out.println("Sum: " + (first + second));
        } catch (NumberFormatException e) {
            System.out.println("Both arguments must be valid integers.");
        }
    }
}

If the program is run with arguments 20 and 30, the output is:

Sum: 50

This example first checks that two arguments exist, then converts each argument into an integer and calculates the sum. It also handles invalid numeric arguments.

16. Common Mistakes and Best Practices

Common Mistake Problem Best Practice
Using Integer.parseInt("10.5") A decimal string is not a valid integer representation. Use Double.parseDouble() if a decimal is expected.
Ignoring NumberFormatException Invalid input may terminate normal program flow. Validate input and handle expected parsing errors.
Assuming "yes" parses to true Boolean.parseBoolean() returns false for this text. Define and validate accepted Boolean representations.
Parsing without considering ranges A valid-looking number may exceed the target type's range. Choose an appropriate type and handle overflow-range errors.
Parsing text with currency symbols Text such as "$100" is not a plain numeric string. Validate and normalize according to a clearly defined input format.
Using charAt(0) on an empty string The call throws an index exception. Check the string length before accessing a character.
Assuming parse methods return wrapper objects Parsing methods return primitive values. Use valueOf() when a wrapper object is needed.

17. Practical Exercise

Write a Java program that converts the following strings into primitive values:

  • "45" into an int.
  • "78.5" into a double.
  • "true" into a boolean.
  • "A" into a char.

Print each converted value and calculate the sum of the integer and decimal values.

Sample Solution

public class PrimitiveConversionExercise {
    public static void main(String[] args) {
        String integerText = "45";
        String decimalText = "78.5";
        String booleanText = "true";
        String characterText = "A";

        int number = Integer.parseInt(integerText);
        double decimal = Double.parseDouble(decimalText);
        boolean status = Boolean.parseBoolean(booleanText);

        if (characterText.isEmpty()) {
            System.out.println("Character input is empty.");
            return;
        }

        char letter = characterText.charAt(0);

        System.out.println("Integer: " + number);
        System.out.println("Double: " + decimal);
        System.out.println("Boolean: " + status);
        System.out.println("Character: " + letter);
        System.out.println("Sum: " + (number + decimal));
    }
}

Expected Output:

Integer: 45
Double: 78.5
Boolean: true
Character: A
Sum: 123.5

18. Interview Questions and Answers

Q1. What is string parsing in Java?

String parsing is the process of interpreting a string and converting it into a suitable data type, such as an integer, decimal, or Boolean value.

Q2. Which method converts a string into an int?

Integer.parseInt() converts a valid integer string into a primitive int.

Q3. What is the difference between parseInt() and valueOf()?

Integer.parseInt() returns a primitive int, whereas Integer.valueOf() returns an Integer wrapper object.

Q4. Which method converts a string into a double?

Double.parseDouble() converts a valid floating-point string into a primitive double.

Q5. What exception occurs when invalid numeric text is parsed?

Java numeric parsing methods typically throw NumberFormatException when the input is not valid for the target numeric type.

Q6. Can a string be converted directly into a char using a parse method?

No. Java does not provide a Character.parseChar() method. A character can be obtained from a non-empty string using charAt(), with Unicode considerations for characters that require multiple UTF-16 code units.

Q7. What does Boolean.parseBoolean("yes") return?

It returns false, because only a case-insensitive match for "true" returns true.

Q8. Why should invalid input be handled with try-catch?

Because malformed numeric input can throw an exception. Handling it lets the program display a useful error message and continue safely where appropriate.

Q9. How can whitespace be removed before parsing?

Use trim() or strip() on the string before passing it to the parsing method.

Q10. Can Integer.parseInt() convert a value larger than the int range?

No. If the value is outside the supported range of int, the method throws NumberFormatException. Use Long.parseLong() when the value fits within the range of long.

19. Quick Revision Checklist

  • Understand why strings must be converted before numeric calculations.
  • Remember the parsing methods for byte, short, int, long, float, and double.
  • Know that Boolean.parseBoolean() returns true only for text equal to "true", ignoring case.
  • Use charAt() to obtain a character from a non-empty string.
  • Understand the difference between parse... and valueOf().
  • Handle invalid numeric strings using suitable validation and exception handling.
  • Check number ranges and clean up permitted whitespace before parsing.
  • Practice converting command-line arguments and user input into primitive values.

20. Conclusion

Converting strings into primitive values is a fundamental Core Java skill. Java provides methods such as Integer.parseInt(), Double.parseDouble(), Float.parseFloat(), Long.parseLong(), and Boolean.parseBoolean() to interpret text as primitive values. For characters, use methods such as charAt() after checking the input. Understanding valid formats, type ranges, whitespace, and exception handling helps you create reliable programs that process real-world input correctly.

Continue learning Java fundamentals through the JustAcademy Core Java Training Course. You can also register for a course demo or visit the JustAcademy official website.

Previous Next
whatsapp